$(document).ready(function() {
    /* 搜索页面 */
    /*$("#text1").on("click",function(){
        alert("hellworl");
    });*/

    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //获取全局数据

    let categoryId = $.getUrlParam('categoryId');
    let keyword=$.getUrlParam('keyword');
    let length =8;  //每页显示条数
    let page=1;     //默认第一页


    let ajaxFun=function (categoryId,keyword,page,length){
        var url;
        if(keyword==null){
            url="/agriecomIndex/search/getProByParentId?categoryId="+categoryId+"&page="+page+"&limit="+length;
        }else
            url="/agriecomIndex/search/categoryAndKeyword?categoryId="+categoryId+"&keyword="+keyword+"&page="+page+"&limit="+length;
        $.ajax({
        url: url,
        dataType: "json",
        type: "GET",
        success: function (data) {
            if(data.count<=length){     //不分页
                   $(".pages").remove();
            }else{

                $("#Pagination").pagination(data.count, {
                    num_edge_entries: 1, //边缘页数
                    num_display_entries: 3, //主体页数
                    callback: pageselectCallback,
                    items_per_page: length, //每页显示1项
                    current_page:page-1,
                    prev_text: "前一页",
                    next_text: "后一页"
                });
                /*
                *       GO页面跳转
                */
                $(".searchPage a").bind("click",function(){
                    window.location="/agriecomIndex/search/forward?categoryId="+categoryId+"&keyword="+keyword;
                });

                let countPage=data.count%length==0?data.count/length:parseInt(data.count/length)+1;
                $(".page-sum strong").html(countPage);
                $(".page-go input").focusout(function(){
                    let desPage=$(".page-go input").val();
                    if (desPage <= countPage &&desPage!=""&&desPage>0) {
                        $(".searchPage a").unbind('click');
                        $(".searchPage a").bind('click',function(){
                            var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                            parentDiv.html("");
                            parentDiv.append(childDiv);
                            if(keyword==null)
                                ajaxFun(categoryId, null, desPage, length);
                            else
                                ajaxFun(categoryId, keyword, desPage, length);
                        });
                    }
                })
                function pageselectCallback(page_index, jq){
                    let childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                    parentDiv.html("");
                    parentDiv.append(childDiv);
                    ajaxFun(categoryId,keyword,page_index+1,length);
                    return false;
                }

            }
            var parentDiv=$(".grid-uniform-category");



            $.each(data.data,function(i,ele){
                //回显
                var imgDiv=$(".product-image")[i];
                $(imgDiv.children[0]).attr("href","/product.html?id="+ele.produceId);
                $(imgDiv.children[0].children[0]).attr("src",ele.produceImg);
                var num=i+1;
                //star
                $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[1]).remove();
                $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[0]).after(`<div class="rating-star">
														<span class="spr-badge" id="spr_badge_3008529987" data-rating="0.0">
															<span class="spr-starrating spr-badge-starrating">
																
															</span>
															<span class="spr-badge-caption"> </span>
														</span>
                                    </div>`);


                //产品名
                $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("");
                $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("<a href='"+ele.produceId+"'>"+ele.produceName+"</a>");
                //价格
                var oldPrice=parseFloat(ele.price)+18;
                $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("");
                $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("<strong>On Sale</strong>" +
                    "<span class=\"money\" data-currency-usd=\"$19.99\">"+ele.price+ele.unit+"</span>" +
                    "<span class=\"visually-hidden\">Regular price</span>" +
                    "<s><span class=\"money\" data-currency-usd=\"$24.99\">"+oldPrice+ele.unit+"</span></s>");
                //排列方式切换（商品简介）
                $($(".list-mode-description")[i]).html("");
                $($(".list-mode-description")[i]).html(ele.produceBrief);
                //联系商家          ele.produceId

                $($(".add-to-cart-form form div")[i]).html("");
                $($(".add-to-cart-form form div")[i]).html('<a href="/product.html?id='+ele.produceId+'" class="btn btn-1 add-to-cart" title="call now">\n' +
                    '                                                        <i class="fa fa-shopping-cart"></i>联系商家</span>\n' +
                    '                                                    </a>');



                //拼接
                var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                parentDiv.append(childDiv);
                if (ele.remarks=="null"){
                    starChange('span#spr_badge_3008529987',2,i);
                } else
                    starChange('span#spr_badge_3008529987',ele.remarks,i);
            })

            //星星变化
            //最后一个是索引值
            //starChange('span#spr_badge_3008529987',4,0);





            $(".grid-uniform-category>div:last-child").empty();
        }
    });
    }
    ajaxFun(categoryId,keyword,page,length);
    //热卖商品
    $.ajax({
        url: "/agriecomIndex/search/hots?page=1&limit=3",
        dataType: "json",
        type: "GET",
        sync:false,
        success: function (data) {          //只取前三个数据
            $.each(data,function(i,ele){
                var num=i+1;
                var div=$(".sb-content>div:nth-child("+num+")");

                $(div.find("a")[0]).attr("href",ele.produceId);                         //图片链接
                $(div.find("a")[0].children[0]).attr("src",ele.produceImg.split(",")[0]);//取第一张放入
                $(div.find("a")[1]).attr("href","/product.html?id="+ele.produceId);
                $(div.find("a")[1]).html("");
                $(div.find("a")[1]).html(ele.produceName);
                $(div.find("a")[1]).append(`</br></br><div class="rating-star">
														<span class="spr-badge" id="spr_badge_3008529731" data-rating="5.0">
														<span class="spr-starrating spr-badge-starrating">
														
														</span>
														<span class="spr-badge-caption">
														1 review </span>
														</span>
                                                    </div>`);
                $($(div.find("p")[1]).children("span")).html(ele.price+ele.unit);
                if (ele.remarks=="null"){
                    starChange('span#spr_badge_3008529731',2,i);
                }else
                 starChange('span#spr_badge_3008529731',ele.remarks,i);
            })
            //最后一个参数写i
            // starChange('span#spr_badge_3008529731',4,0);
        }

    })
    //广告
    $.ajax({
        url: "/agriecomIndex/search/ad",
        dataType: "json",
        type: "GET",
        success: function (data) {
            $(".slider-banner-wrapper img").attr("src",data[0].pic);

        }}
    )

})

/*
* n=2是星星个数的默认值 然后str 传的是 i标签父级的父级span的id   span#spr_badge_3008529987
* index是span#spr_badge_.......元素的索引值
* */

let starChange = (str,n=2,index=0)=>{
        let temp = `<i class="spr-icon spr-icon-star" style=""></i>`;
        for(let i=0;i<n;i++){
            $(str).eq(index).find('span.spr-starrating.spr-badge-starrating').append(temp);
        }
}


